{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "import json\n",
    "import logging\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import sys\n",
    "import ipywidgets as widgets\n",
    "from pprint import pprint\n",
    "from nupic.research.frameworks.pytorch.imagenet_experiment import ImagenetExperiment\n",
    "from projects.imagenet.experiments_superconvergence import CONFIGS\n",
    "logging.disable(sys.maxsize)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Select experiment "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    name = selection.value\n",
    "except:\n",
    "    name = \"default\"\n",
    "selection = widgets.Dropdown(options=CONFIGS.keys(), value=name)\n",
    "selection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "name = selection.value\n",
    "config = CONFIGS[name]\n",
    "config.update(name=name)\n",
    "pprint(config)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Compute all LR values by simulating training"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_lr(exp):\n",
    "    lr = []\n",
    "    total_images = len(exp.train_loader.dataset)\n",
    "    for epoch in range(exp.epochs):\n",
    "        exp.pre_epoch(epoch)\n",
    "        total_batches = -(-total_images // exp.batch_size)\n",
    "        for batch in range(total_batches):\n",
    "            exp.pre_batch(exp.model, batch, epoch)\n",
    "            exp.optimizer.step()\n",
    "            lr.append(exp.get_lr()[0])\n",
    "            exp.post_batch(exp.model, 0, batch, epoch)\n",
    "        exp.post_epoch(epoch)\n",
    "    return lr\n",
    "\n",
    "exp = ImagenetExperiment()\n",
    "exp.setup_experiment(config)\n",
    "lr = compute_lr(exp)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot experiment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(lr, label=name)\n",
    "plt.title(\"Leaning rate schedule\")\n",
    "plt.xlabel(\"batches\")\n",
    "plt.ylabel(\"learning rate\")\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Save results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save config\n",
    "with open(f\"{name}.json\", \"w\") as fp:\n",
    "    json.dump(config, fp, default=lambda o: str(o))\n",
    "\n",
    "# Save LR by epochs\n",
    "lr_per_epoch = np.array_split(lr, exp.epochs)\n",
    "df = pd.DataFrame(lr_per_epoch, index=range(len(lr_per_epoch)), columns=range(len(lr_per_epoch[0])))\n",
    "df.to_csv(f\"{name}.csv\", header=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Show LR by epochs table (slow)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.set_option(\"display.max_rows\", None)\n",
    "pd.set_option(\"display.max_columns\", None)\n",
    "df"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
